package com.ruoyi.web.controller.biz;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.biz.model.dto.ConfigDto;
import com.ruoyi.biz.model.excel.OldBizSectorExcel;
import com.ruoyi.biz.model.resp.BizSectorResp;
import com.ruoyi.biz.model.resp.ExportResp;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.DbArray;
import com.ruoyi.web.model.ProjectField;
import com.ruoyi.web.model.ProjectFieldParent;
import com.ruoyi.web.model.RuleModel;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.biz.domain.BizSector;
import com.ruoyi.biz.service.BizSectorService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目板块管理Controller
 *
 * @author ruoyi
 * @date 2024-12-19
 */
@RestController
@RequestMapping("/biz/bizSector")
public class BizSectorController extends BaseController {
    @Autowired
    private BizSectorService bizSectorService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Anonymous
    @GetMapping(value = "/setDg")
    public AjaxResult setDg() {
        bizSectorService.setDg();
        return success("ok");
    }

    @Anonymous
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestPart("file") MultipartFile file) throws Exception {
        String message = bizSectorService.importExcel(file);
        return success(message);
    }

    @Anonymous
    @PostMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        List<OldBizSectorExcel> excels = new ArrayList<>();
        OldBizSectorExcel tmp = new OldBizSectorExcel();
        tmp.setName("示例一级");
        tmp.setCode("test1");
        tmp.setParentCode("");
        OldBizSectorExcel tmp2 = new OldBizSectorExcel();
        tmp2.setName("示例二级");
        tmp2.setCode("test12");
        tmp2.setParentCode("test1");
        OldBizSectorExcel tmp3 = new OldBizSectorExcel();
        tmp3.setName("示例三级");
        tmp3.setCode("test123");
        tmp3.setParentCode("test12");
        excels.add(tmp);
        excels.add(tmp2);
        excels.add(tmp3);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = System.currentTimeMillis() + "";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), OldBizSectorExcel.class).sheet("数据").doWrite(excels);
    }

    /**
     * 查询项目板块管理列表
     */
    @GetMapping("/list")
    public AjaxResult list(BizSector bizSector) {
        List<BizSectorResp> list = bizSectorService.list(bizSector);
        return success(list);
    }

    /**
     * 导出项目板块管理列表
     */
    @Log(title = "项目板块管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        List<ExportResp> list = bizSectorService.export();
        ExcelUtil<ExportResp> util = new ExcelUtil<>(ExportResp.class);
        util.exportExcel(response, list, "项目板块数据");
    }

    /**
     * 获取项目板块管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizSectorService.selectById(id));
    }

    /**
     * 新增项目板块管理
     */
    @Log(title = "项目板块管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizSector bizSector) {
        bizSectorService.beforeSave(bizSector);
        return AjaxResult.success();
    }

    /**
     * 修改项目板块管理
     */
    @Log(title = "项目板块管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizSector bizSector) {
        bizSectorService.beforeSave(bizSector);
        return AjaxResult.success();
    }

    /**
     * 删除项目板块管理
     */
    @Log(title = "项目板块管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bizSectorService.deleteByIds(ids));
    }

    @GetMapping("/getConfig")
    public AjaxResult getConfig(Long id) {
        BizSector bizSector = bizSectorService.selectById(id);
        if (bizSector == null || bizSector.getFields() == null) {
            return AjaxResult.success(new ArrayList<>());
        }
        return AjaxResult.success(bizSector);
    }

    @GetMapping("/getConfigAll")
    public AjaxResult getConfigAll(Long id) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:fields.json");
        InputStream inputStream = resource.getInputStream();
        String json = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        List<ProjectFieldParent> fieldList = JSON.parseArray(json, ProjectFieldParent.class);
        BizSector bizSector = bizSectorService.selectById(id);
        if (bizSector != null && !CollectionUtils.isEmpty(bizSector.getFields())) {
            for (ProjectFieldParent fieldParent : fieldList) {
                for (ProjectField field : fieldParent.getChildren()) {
                    for (Object f : bizSector.getFields()) {
                        if (field.getCode().equals(f)) {
                            field.setShow(true);
                            break;
                        }
                    }
                    for (Object f : bizSector.getRequireds()) {
                        if (field.getCode().equals(f)) {
                            field.setRequired(true);
                            break;
                        }
                    }
                }
            }
        }
        return AjaxResult.success(fieldList);
    }

    @PostMapping("/saveConfigAll")
    public AjaxResult saveConfigAll(@RequestBody ConfigDto req) {
        BizSector bizSector = bizSectorService.selectById(req.getId());
        if (bizSector != null) {
            List<String> fields = new ArrayList<>();
            List<String> requireds = new ArrayList<>();
            List<ProjectField> requiredInfos = new ArrayList<>();
            for (ProjectFieldParent fieldParent : req.getData()) {
                List<String> fields0 = fieldParent.getChildren().stream().filter(ProjectField::getShow).map(ProjectField::getCode).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(fields0)) {
                    fields.addAll(fields0);
                }
                List<String> requireds0 = fieldParent.getChildren().stream()
                        .filter(ProjectField::getRequired)
                        .filter(r -> fields.contains(r.getCode()))
                        .map(ProjectField::getCode)
                        .collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(requireds0)) {
                    requireds.addAll(requireds0);
                }
                List<ProjectField> requiredInfos0 = fieldParent.getChildren().stream()
                        .filter(ProjectField::getRequired)
                        .filter(r -> fields.contains(r.getCode())).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(requiredInfos0)) {
                    requiredInfos.addAll(requiredInfos0);
                }
            }
            JSONObject map = new JSONObject();
            for (ProjectField field : requiredInfos) {
                map.put(field.getCode(), Arrays.asList(new RuleModel(field.getName())));
            }
            bizSector.setFields(new DbArray(fields));
            bizSector.setRequireds(new DbArray(requireds));
            bizSector.setRequiredInfo(map);
            bizSectorService.updateById(bizSector);
        }
        return AjaxResult.success();
    }
}
